package com.chat.security.service;

import com.chat.security.exception.TokenInvalidateException;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;

//@Setter
@Component
public class JwtTokenService {

    @Value("${czh.securityKey}")
    private final String securityKey = "abc";

    public static final String LOGIN_USER_KEY = "asda";

    public String getJwtToken(Map<String, Object> claims) {
        final String compact = Jwts.builder()
                .addClaims(claims)
//                .setExpiration()
                .signWith(SignatureAlgorithm.HS256, securityKey.getBytes(StandardCharsets.UTF_8)).compact();
        return compact;
    }

    public Map<String, Object> getClaims(String token) {
        final Jwt parse ;
        try {
           parse =  Jwts.parser().setSigningKey(securityKey.getBytes(StandardCharsets.UTF_8))
                    .parse(token);
        }catch (Exception e){
            throw new TokenInvalidateException("token 失效");
        }
        return (Map<String, Object>) parse.getBody();
    }
}
